import service from './service'
import exportService from './export-service'
import qs from 'qs'
// 请求头
function getHeaders (isFormData) {
  return {
    'Content-Type': isFormData ? 'application/x-www-form-urlencoded' : 'application/json;charset=UTF-8',
    'menuId': sessionStorage.getItem('menuId') || 2,
    'btnId': sessionStorage.getItem('buttonId') || 2
  }
}
/**
 * http请求
 * @param {string} apiUrl 接口地址
 * @param {string} type 请求方式
 * @param {string} data 请求参数
 * @param {boolean} isFormData 是否为form请求，默认为否
 */
export function Request (apiUrl, type, data, isFormData = false) {
  let config = {
    url: apiUrl,
    method: type,
    headers: getHeaders(isFormData),
  }
  if (type === 'get') {
    config.params = data;
  } else {
    config.data = isFormData ? qs.stringify(data) : data;
  }
  return service(config)
}
// 文件导出
export function RequestForExportFile (apiUrl, type, data, isFormData) {
  let config = {
    url: apiUrl,
    method: type,
    headers: getHeaders(isFormData),
    responseType: 'arraybuffer'
  }
  if (type === 'get') {
    config.params = data;
  } else {
    config.data = isFormData ? qs.stringify(data) : data;
  }
  return exportService(config)
}

const isResponseSuccess = (response) => {
  return response && response.status && response.status === '0';
}

export const SupplierRequest = async (options) => {
  const { url, type, data = {}, isFormData, isExport, loadingFn } = options;
  let requestMethord = isExport ? RequestForExportFile : Request
  if (loadingFn) loadingFn(true)
  try {
    const res = await requestMethord(url, type, data, isFormData);
    if (loadingFn)loadingFn(false)
    if (isExport) {
      return res;
    }
    if (isResponseSuccess(res)) {
      return res;
    }
  } catch (err) {
    if (loadingFn)loadingFn(false)
  }
}
